/*
 * @Author Shunzi
 * @Date 2021-07-12 16:38:28
 * @LastEditTime 2021-07-17 18:31:11
 * @LastEditors Shunzi
 * @Description
 * @FilePath /BFFNodeServer/controllers/books.js
 */
const express = require("express");
const router = express.Router();
const request = require("../request");
const Controller = require("./controller");
const ResultData = require("../utils/ResultData");

class Books extends Controller {
  constructor(...props) {
    super(...props);
  }

  async actionBooks(req, res, next) {
    if (req.method === "GET") {
      try {
        const params = {
          page: req.query?.page || 1,
          pageSize: 5,
        };
        const datas = await request.get("bookapis", params);
        res.render("books", { nav: "books", datas });
      } catch {
        next();
      }
    }
  }

  async actionCreate(req, res, next) {
    if (req.method === "GET") {
      res.render("create", { nav: "create" });
    } else if (req.method === "POST") {
      try {
        const r = await request.post("bookapis", req.body);
        if (String(r) == "1") {
          res.json(new ResultData(1, {}));
        } else {
          res.json(new ResultData(0, {}));
        }
      } catch (err) {
        res.json(new ResultData(0, {}));
      }
    }
  }

  async actionDelete(req, res, next) {
    if (req.method === "GET") {
      const id = req.query.id;
      try {
        const r = await request.delete(`bookapis/${id}`);
        if (Number(r) === 1) {
          res.json(new ResultData(1, {}));
        } else {
          res.json(new ResultData(0, {}, "删除失败"));
        }
      } catch {
        res.json(new ResultData(0, {}, "删除失败"));
      }
    }
  }
}

module.exports = Books;
